package com.hsjk.szwj.module.pay.controller.app.order;

import cn.hutool.core.util.ObjectUtil;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.controller.AbstractPayOrderController;
import com.hsjk.szwj.module.pay.controller.app.order.vo.QueryPayOrderReqVO;
import com.hsjk.szwj.module.pay.controller.app.order.vo.QueryPayOrderRespVO;
import com.hsjk.szwj.module.pay.dal.dataobject.CommonPayResult;
import com.hsjk.szwj.module.pay.dal.dataobject.order.PayOrderDO;
import com.hsjk.szwj.module.pay.dal.dataobject.system.MchInfoDO;
import com.hsjk.szwj.module.pay.service.ConfigContextQueryService;
import com.hsjk.szwj.module.pay.service.IMchInfoService;
import com.hsjk.szwj.module.pay.service.PayOrderService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/24 15:37
 **/
@Tag(name = "应用端 - 订单查询相关接口")
@RestController
@RequestMapping("/pay")
@Validated
public class QueryOrderController extends AbstractPayOrderController {

    @Resource
    private PayOrderService payOrderService;
    @Resource
    private ConfigContextQueryService configContextQueryService;
    @Resource
    private IMchInfoService mchInfoService;

    /**
     * 查单接口
     **/
    @RequestMapping("/query")
    public CommonPayResult queryOrder() {
        //获取参数 & 验签
        QueryPayOrderReqVO rq = getRQByWithMchSign(QueryPayOrderReqVO.class);

        if (ObjectUtil.isNull(rq.getMchOrderId()) && ObjectUtil.isNull(rq.getPayOrderId())) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "mchOrderNo 和 payOrderId不能同时为空");
        }
        MchInfoDO mchInfoDO = mchInfoService.getMchInfoById(rq.getMchId());
        PayOrderDO payOrder = payOrderService.queryMchOrder(mchInfoDO.getId(),
                rq.getPayOrderId(), rq.getMchOrderId());
        if (payOrder == null) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "订单不存在");
        }

        QueryPayOrderRespVO bizRes = QueryPayOrderRespVO.buildByPayOrder(payOrder);
        return CommonPayResult.okWithSign(bizRes,
                configContextQueryService.queryMchApp(rq.getMchId(),
                        rq.getAppId()).getAppSecret());
    }

}
